/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.aggregate_exception;

import java.util.LinkedList;
import java.util.List;

import junit.framework.AssertionFailedError;

public class AggregatingThrower implements Thrower {
	private final List<AssertionFailedError> errors = new LinkedList<AssertionFailedError>();

	private int errorThreshold = 0;

	public void setThreshold(int errorThreshold) {
		this.errorThreshold = errorThreshold;
	}

	public void errorEvent(AssertionFailedError error) {
		errors.add(error);

		if (errorThreshold >= 0 && errors.size() > errorThreshold) {
			dispatchError();
		}
	}

	public void dispatchError() {
		if (errors.size() == 1) {
			throw errors.get(0);
		}
		else if (errors.size() > 1) {
			throw new AggregateAssertionFailedError(errors);	
		}
	}

	public void clearError() {
		errors.clear();
	}
}
